#!/bin/bash
scriptWorkd=$(cd "$(dirname $0)";pwd)

### ========= 全局变量 ===========
program=${HOME}/bin
### ==============================

### ========= 前置文件 ===========
if [[ -f ${HOME}/bin/basic_func.sh ]];then  ### 存在才载入
    source ${HOME}/bin/basic_func.sh
elif [[ -f ${scriptWorkd}/../bin/basic_func.sh ]];then
    source ${scriptWorkd}/../bin/basic_func.sh
elif [[ -f ./bin/basic_func.sh ]];then
    source ./bin/basic_func.sh
fi
### ==============================


function installNvim() {
set +e
    ### 如果能用snap安装，就用snap
    sudo snap install nvim --classic
    if [[ $? == 0 ]];then
        return 0
    fi
set -e

    echo -e "${hintStrWarning}snap失败，使用源码安装"
    
    # 源码安装
    last_dir=$(pwd)
    install_to=${program}/neovim

    ### 安装依赖
    sudo apt-get install -y gettext cmake pip

    ### 下载并解压源码
    mkdir -p ./temp
    cd ./temp
    if [[ -d neovim-0.9.5 ]];then
	    echo -e "之前已经编译过nvim"
        	cd "${last_dir}"
	    return 0
    fi
    # mv v0.9.5.tar.gz neovim-0.9.5.tar.gz
    
    flag1=$((0))
    for i in "${!proxy_list[@]}"; do
        echo -e "${hintStrProcessing}尝试下载: ${proxy_list[1]}/neovim/neovim/archive/refs/tags/v0.9.5.tar.gz"
        if timeout 120 wget ${proxy_list[1]}/neovim/neovim/archive/refs/tags/v0.9.5.tar.gz -O neovim-0.9.5.tar.gz; then
            echo -e "${hintStrSucceed}下载成功"
	    flag1=$((1))
            break;
        else
            echo -e "${hintStrWarning}失败，尝试下一个链接"
        fi
    done
    if [[ $flag1 == 0 ]];then
        echo -e "${hintStrFailed}所有下载都失败"
        exit 1
    fi
    tar -zxf neovim-0.9.5.tar.gz

    ### 安装
    cd neovim-0.9.5
    mkdir -p ./.deps/build
    sed -i 's#github.com#githubfast.com#g' ./cmake.deps/CMakeLists.txt
    make CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_INSTALL_PREFIX=${install_to}
    echo -e "Nvim Will be installed to ${yellow}${install_to}${normal}"
    sleep 5
    make install

    ### 加入环境变量
    if [[ ! -f ~/.envrc ]]; then
	    echo "新建"
	    echo " ">|~/.envrc
    fi
    insert_env 'PATH' "${install_to}/bin" ${HOME}/.envrc 
    
    ### 把python依赖装上再说
set +e
    pip install neovim        
    pip install commitizen
set -e
    echo -e "${blue}Done neovim${normal}"
    cd "${last_dir}"
    # rm -rf ./temp
    unset last_dir
    unset install_to
set +e
}

function main() {
set +e
    ## 开始信息
    echo -e "${blue4}\n$(basename $0)\n${normal}"

    sudo apt install -y python
    sudo apt install -y python3

set -e

    installNvim
    pip install neovim

    echo -e "${hintStrProcessing}\nNeovim Installed\nnvim安装完成${normal}\n"

    ## 结束信息
    echo -e "${green4}\n$(basename $0)\n${normal}"
}
main $@
